<template>
  <div class="attr_wrapper">
    <el-space fill>
      <Category
        ref="category"
        :disabled="!isShow"
        @resetTable="resetTable"
        @handleChangeC3="handleChangeC3"
      />
      <el-card class="attr_card_table">
        <!-- 展示属性table -->
        <template v-if="isShow">
          <el-button
            type="primary"
            icon="Plus"
            style="margin-bottom: 20px"
            :disabled="isDisabled"
            @click="addAttr"
          >
            添加平台属性
          </el-button>
          <el-table :data="tableData" :border="true">
            <el-table-column
              type="index"
              label="序号"
              width="100"
              align="center"
            />
            <el-table-column prop="attrName" label="属性名称" width="200" />
            <el-table-column prop="logoUrl" label="属性值名称">
              <template #default="{ row }">
                <el-tag
                  v-for="o in row.attrValueList"
                  :key="o.id"
                  type="primary"
                  style="margin: 0 5px"
                >
                  {{ o.valueName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" width="200">
              <template #default="{ row, $index }">
                <el-button
                  type="primary"
                  icon="edit"
                  @click="editAttr(row, $index)"
                >
                  编辑
                </el-button>
                <el-button type="danger" icon="delete" @click="delAttr(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 添加属性table -->
        <template v-else>
          <el-form>
            <el-form :model="form" :inline="true">
              <el-form-item label="属性名称" prop="attrName">
                <el-input
                  v-model="form.attrName"
                  placeholder="请输入属性名称"
                />
              </el-form-item>
            </el-form>
          </el-form>
          <el-button
            type="primary"
            icon="Plus"
            style="margin-bottom: 20px"
            :disabled="!form.attrName"
            @click="addAttrValue"
          >
            添加属性值
          </el-button>
          <el-table :data="form.attrValueList" :border="true">
            <el-table-column
              type="index"
              label="序号"
              width="100"
              align="center"
            />
            <el-table-column prop="attrName" label="属性值名称">
              <template #default="{ row, $index }">
                <el-input
                  v-if="row.isEdit"
                  :ref="(vc: any) => (inputRefs[$index] = vc)"
                  placeholder="请输入属性值名称"
                  v-model="row.valueName"
                  @blur="changeMode(row, $index)"
                />
                <div v-else @click="toEdit(row, $index)">
                  {{ row.valueName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  icon="delete"
                  @click="delAttrItem($index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            style="margin-top: 20px"
            @click="saveAttr"
            :disabled="le"
          >
            保存
          </el-button>
          <el-button style="margin-top: 20px" @click="cancel">取消</el-button>
        </template>
      </el-card>
    </el-space>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { addOrUpdateAttrMethod, delGategory } from '@/api/product/attr'
import { ElMessage, ElMessageBox } from 'element-plus'
import '@/styles/product/attr.less'

let category = ref()
let isDisabled = ref(true)
let tableData = ref<any>([])
let isShow = ref(true)
let form = reactive<any>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3
})
let category3Id: any = ''
const inputRefs = ref<HTMLElement[]>([]) // 存储遍历的input的ref

const le = computed(() => {
  return form.attrValueList.length > 0 ? false : true
})

// 一/二级分类回调
const resetTable = (value: any) => {
  tableData.value = []
}

// 三级分类回调
const handleChangeC3 = (
  data: any,
  c1: number | string,
  c2: number | string,
  c3: number | string
) => {
  tableData.value = data
  category3Id = c3
  isDisabled.value = c3 ? false : true
}

// 添加属性
const addAttr = () => {
  Object.assign(form, {
    attrName: '',
    attrValueList: [],
    categoryId: category3Id,
    categoryLevel: 3
  })
  delete form.id
  isShow.value = false
}

// 取消添加/编辑
const cancel = () => {
  isShow.value = true
}

// 编辑属性
const editAttr = (data: any, index: number) => {
  isShow.value = false
  Object.assign(form, JSON.parse(JSON.stringify(data)))
}

//删除方法
const delGategoryMethod = async (id: any) => {
  let res: any = await delGategory(id)
  if (res.code === 200) {
    ElMessage.success(res.message)
    category.value.selectC3()
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 删除属性
const delAttr = (data: any) => {
  ElMessageBox.confirm(`确定删除${data.attrName}属性吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delGategoryMethod(data.id)
  })
}

// 添加属性值
const addAttrValue = () => {
  form.attrValueList.push({
    valueName: '',
    isEdit: true
  })
  nextTick(() => {
    inputRefs.value[inputRefs.value.length - 1].focus()
  })
}

// 删除属性值
const delAttrItem = (idx: number) => {
  form.attrValueList.splice(idx, 1)
}

// 控制编辑与只读模式的方法
const changeMode = (data: any, idx: number) => {
  // 非空判断
  if (data.valueName.trim() == '') {
    form.attrValueList.splice(idx, 1)
    return ElMessage.error('属性值不能为空')
  }
  // 重复判断
  let isRepeat = form.attrValueList.some((item: any) => {
    // 不检查自己
    if (item != data) {
      return item.valueName === data.valueName
    }
  })
  if (isRepeat) {
    form.attrValueList.splice(idx, 1)
    return ElMessage.error('属性值不能重复')
  }
  data.isEdit = false
}

const toEdit = (data: any, idx: number) => {
  data.isEdit = true
  nextTick(() => {
    inputRefs.value[idx].focus()
  })
}

// 保存
const saveAttr = async () => {
  let state = form.attrValueList.some((o: any) => !o.valueName)
  if (state) {
    return ElMessage.warning('属性值不能为空！')
  }
  let res: any = await addOrUpdateAttrMethod(form)
  if (res.code === 200) {
    isShow.value = true
    ElMessage.success(res.message)
    category.value.selectC3()
  } else {
    ElMessage.error(res.message)
  }
}
</script>

<style scoped></style>
